<?php


namespace app\zhongcan\controller;


use app\zhongcan\model\NavModel;
use app\zhongcan\validate\NavValidate;
use cmf\controller\AdminBaseController;

class NavController extends AdminBaseController
{
    //列表
    public function index()
    {
        $keyword = input('keyword', '');
        $where = [];
        if ($keyword) {
            $where[] = ['title|p_id', 'like', '%' . $keyword . '%'];
        }
        $list = NavModel::order('list_order', 'desc')
            ->where($where)
            ->paginate(2);
        $this->assign('nav', $list);
        return $this->fetch();
    }

    //显示添加页面
    public function add()
    {
        return $this->fetch();
    }

    //添加的提交
    public function addPost()
    {
        //接收数据
        $data = input('post.');
        //验证数据（验证器)
        $validate = new NavValidate();
        $res = $validate->scene('add')->check($data);
        if (!$res) {
            $this->error($validate->getError());
        }

        //然后入库
        if (NavModel::create($data)) {
            $this->success('添加成功','Nav/index');
        } else {
            $this->success('添加失败');
        }
    }

    //显示编辑页面
    public function edit()
    {
        $id = input('id/d');
        $nav = NavModel::find($id);
        $this->assign('nav', $nav);
        return $this->fetch();
    }

    //添加的提交
    public function editPost()
    {
        //接收数据
        $data = input('post.');
        $validate = new NavValidate();
        $res = $validate->scene('edit')->check($data);
        if (!$res) {
            $this->error($validate->getError());
        }
        //先查询数据
        $nav = NavModel::find($data['id']);
        if(!$nav){
            $this->error('未查询到数据');
        }
        $nav->title = $data['title'];
        //然后入库
        if ($nav->save()) {
            $this->success('保存成功','Nav/index');
        } else {
            $this->success('保存失败');
        }
    }
    public function del()
    {
        $id = input('id/d');
        $nav = NavModel::destroy($id);
        if ($nav) {
            $this->success('删除成功','Nav/index');
        } else {
            $this->success('删除失败');
        }
    }
    public function order()
    {

        parent::listOrders(new NavModel());
        $this->success('排序成功');
    }
}